package com.ruoyi.flowable.service;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import org.flowable.engine.HistoryService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.history.HistoricProcessInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class WorkFLowService {
    @Autowired
    private HistoryService historyService;
    @Autowired
    private RuntimeService runtimeService;

    /***
     * 删除所有的流程实例
     */
    @Transactional
    public void deleteAllFlowInstance(){
        //未完成的流程实例
        List<HistoricProcessInstance> list = historyService.createHistoricProcessInstanceQuery().unfinished().list();
        if(list!=null&&list.size()>0){
            for(HistoricProcessInstance r:list){
                String procid = r.getId();
                if(StringUtils.isNotBlank(procid)){
                    /***
                     * 删除流程实例----未完成的
                     */
                    try{
                        runtimeService.deleteProcessInstance(procid, "删除流程实例");
                    }catch(Exception e){

                    }
                }
            }
        }
        //已经完成的流程实例
        List<HistoricProcessInstance> list2 = historyService.createHistoricProcessInstanceQuery().finished().list();
        if(list2!=null&&list2.size()>0){
            for(HistoricProcessInstance r:list2){
                String procid = r.getId();
                if(StringUtils.isNotBlank(procid)){
                    /***
                     * 删除流程实例----已完成的
                     */
                    try{
                        historyService.deleteHistoricProcessInstance(procid);
                    }catch(Exception e){

                    }

                }
            }
        }
    }



    @Transactional
    public void deleteFlowInstanceById(String insId){
        //删除正在运行的流程实例
        ProcessInstance runIns = runtimeService.createProcessInstanceQuery().processInstanceId(insId).singleResult();
        if(runIns!=null){
            runtimeService.deleteProcessInstance(insId, "删除流程实例");
        }
        //已经完成的流程实例
        HistoricProcessInstance hisIns = historyService.createHistoricProcessInstanceQuery().processInstanceId(insId).singleResult();
        if(hisIns!=null){
            historyService.deleteHistoricProcessInstance(insId);
        }
    }

}
